package cn.ilikes.tools.nosql.jpa.clients.indexs.index;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import org.apache.lucene.codecs.lucene41.Lucene41Codec;
import org.apache.lucene.index.CheckIndex;
import org.apache.lucene.store.Directory;
import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.hadoops.HadoopFileSystemDirectory;
import cn.ilikes.tools.nosql.jpa.configs.indexs.IndexConfigs;

public class LuceneHadoopIndexSource extends ABLuceneIndexSource {

	private Logger logger = Loggerfactory.instance(LuceneHadoopIndexSource.class);

	private Directory directory;

	public LuceneHadoopIndexSource(IndexConfigs indexConfigs) {
		super(indexConfigs);
	}

	private void setDirectory(Directory directory) {
		this.directory = directory;
	}

	@Override
	protected Directory getLuceneDirectory() {

		return directory;
	}

	@Override
	public void init() {
		Loggerfactory.info(logger, "Start init Lucene hadoop  Index Source ");

		try {
			IndexConfigs indexConfigs = getIndexConfigs();
			Directory directory = new HadoopFileSystemDirectory(indexConfigs);
			Loggerfactory.info(logger, "Start  Check Lucene  Index ");
			CheckIndex checker = new CheckIndex(directory);
			checker.setInfoStream(System.out);
			CheckIndex.Status satus = checker.checkIndex();
			System.out.println("   |||||||||  CheckIndex.Status ||||||||||     "+satus+"        " + satus.clean);
			if(!satus.clean &&satus.numSegments >0){
				Lucene41Codec xxx = new Lucene41Codec();
				checker.fixIndex(satus, xxx);	
			}
			setDirectory(directory);
			Loggerfactory.info(logger, "init Lucene Index Source success ! ");
		} catch (IOException e) {
			Loggerfactory.error(logger, e);
		}
	}

	@Override
	public void close() {
		Loggerfactory.info(logger, "Start Close Lucene Index Source ");
		try {

			directory.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void open() {
		Loggerfactory.info(logger, "Start open  Lucene Index Source ");

	}

}
